package ru.spb.osll.myfit.server;

import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.isA;
import static org.junit.Assert.assertEquals;

import java.io.File;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.LinkedList;

import org.easymock.EasyMockSupport;
import org.junit.Before;
import org.junit.Test;

import ru.spb.osll.myfit.server.fixtureiterator.FileFactory;

public class MyFitClassLoaderFactoryTest extends EasyMockSupport {
  private FileFactory fileFactory;
  private MyFitClassLoaderFactory classLoaderFactory;
  private File depsDir;
  private File fixturesDir;
  private File fitnesseJar;
  private File myfitJar;
  private File fixturesJar;

  @Before
  public void setUp() {
    fileFactory = createStrictMock(FileFactory.class);
    depsDir = createStrictMock(File.class);
    fixturesDir = createStrictMock(File.class);
    fitnesseJar = createStrictMock(File.class);
    myfitJar = createStrictMock(File.class);
    fixturesJar = createStrictMock(File.class);
    classLoaderFactory = new MyFitClassLoaderFactory(fileFactory);
  }

  @Test
  public void testConstructor() throws Exception {
    expect(fileFactory.createFile("lib/deps")).andReturn(depsDir);
    expect(depsDir.list(isA(FilenameFilter.class))).andReturn(new String[] { "fitnesse.jar", "myfit.jar" });
    expect(fileFactory.createFile(depsDir, "fitnesse.jar")).andReturn(fitnesseJar);
    expect(fitnesseJar.toURI()).andReturn(new URI("file://lib/deps/fitnesse.jar"));
    expect(fileFactory.createFile(depsDir, "myfit.jar")).andReturn(myfitJar);
    expect(myfitJar.toURI()).andReturn(new URI("file://lib/deps/myfit.jar"));
    expect(fileFactory.createFile("lib/fixtures")).andReturn(fixturesDir);
    expect(fixturesDir.list(isA(FilenameFilter.class))).andReturn(new String[] { "fixtures.jar" });
    expect(fileFactory.createFile(fixturesDir, "fixtures.jar")).andReturn(fixturesJar);
    expect(fixturesJar.toURI()).andReturn(new URI("file://lib/fixtures/fixtures.jar"));
    replayAll();
    URLClassLoader classLoader = classLoaderFactory.createClassLoader("lib/deps", "lib/fixtures");
    verifyAll();
    assertEquals(3, classLoader.getURLs().length);
    assertEquals("file://lib/deps/fitnesse.jar", classLoader.getURLs()[0].toString());
    assertEquals("file://lib/deps/myfit.jar", classLoader.getURLs()[1].toString());
    assertEquals("file://lib/fixtures/fixtures.jar", classLoader.getURLs()[2].toString());
  }
}
